/**************************************************************************************
 *
 * @(#) HomePageBiz.java
 * @Package com.jgdt.jgdtkasannong_university_gene_backend.biz.content.impl
 **************************************************************************************/
package com.jgdt.jgdtkasannong_university_gene_backend.biz.content.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jgdt.jgdtkasannong_university_gene_backend.biz.content.MenuContentBiz;
import com.jgdt.jgdtkasannong_university_gene_backend.common.enums.SystemCodeEnums;
import com.jgdt.jgdtkasannong_university_gene_backend.common.example.custom.BusinessException;
import com.jgdt.jgdtkasannong_university_gene_backend.common.response.PageRequest;
import com.jgdt.jgdtkasannong_university_gene_backend.common.Sysconstant;
import com.jgdt.jgdtkasannong_university_gene_backend.config.enums.SysValueSetEnums;
import com.jgdt.jgdtkasannong_university_gene_backend.config.enums.template.TemplateContentEnums;
import com.jgdt.jgdtkasannong_university_gene_backend.dto.BaseImgDataDto;
import com.jgdt.jgdtkasannong_university_gene_backend.dto.UpdateContentDto;
import com.jgdt.jgdtkasannong_university_gene_backend.entity.base.BaseInfo;
import com.jgdt.jgdtkasannong_university_gene_backend.entity.base.BaseRegion;
import com.jgdt.jgdtkasannong_university_gene_backend.entity.content.*;
import com.jgdt.jgdtkasannong_university_gene_backend.enums.content.BizTypeEnums;
import com.jgdt.jgdtkasannong_university_gene_backend.enums.content.MediaTypeEnums;
import com.jgdt.jgdtkasannong_university_gene_backend.mapper.content.ContentGeneralMapper;
import com.jgdt.jgdtkasannong_university_gene_backend.mapper.content.MediaMapper;
import com.jgdt.jgdtkasannong_university_gene_backend.mapper.content.MenuContentMapper;
import com.jgdt.jgdtkasannong_university_gene_backend.service.base.BaseInfoService;
import com.jgdt.jgdtkasannong_university_gene_backend.service.base.BaseRegionService;
import com.jgdt.jgdtkasannong_university_gene_backend.service.content.ContentGeneralService;
import com.jgdt.jgdtkasannong_university_gene_backend.service.content.MediaService;
import com.jgdt.jgdtkasannong_university_gene_backend.service.content.MenuContentService;
import com.jgdt.jgdtkasannong_university_gene_backend.service.content.SysMenuService;
import com.jgdt.jgdtkasannong_university_gene_backend.service.sys.SysValueSetService;
import com.jgdt.jgdtkasannong_university_gene_backend.utils.BeanUtils;
import com.jgdt.jgdtkasannong_university_gene_backend.utils.IdUtil;
import com.jgdt.jgdtkasannong_university_gene_backend.utils.ListUtil;
import com.jgdt.jgdtkasannong_university_gene_backend.vo.content.excel.base.BaseImgData;
import com.jgdt.jgdtkasannong_university_gene_backend.vo.content.excel.research_achievements.RepresentativeAchievement;
import com.jgdt.jgdtkasannong_university_gene_backend.vo.content.excel.research_achievements.ResourceProtection;
import com.jgdt.jgdtkasannong_university_gene_backend.vo.content.excel.research_achievements.data.AchievementData;
import com.jgdt.jgdtkasannong_university_gene_backend.vo.content.excel.research_achievements.data.AchievementDataVo;
import com.jgdt.jgdtkasannong_university_gene_backend.vo.content.excel.research_team.KeyMembers;
import com.jgdt.jgdtkasannong_university_gene_backend.vo.content.excel.research_team.TeamLeader;
import com.jgdt.jgdtkasannong_university_gene_backend.vo.content.excel.research_team.data.TeamDataVo;
import com.jgdt.jgdtkasannong_university_gene_backend.vo.content.menu_content.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @description: 菜单内容-biz实现
 * @author: huangAn
 * @createDate: 2025/04/24
 */
@Slf4j
@Service
public class MenuContentBizImpl implements MenuContentBiz {

    @Autowired
    private MenuContentService menuContentService;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private ContentGeneralService contentGeneralService;

    @Autowired
    private MediaService mediaService;

    @Autowired
    private ContentGeneralService contentGeneral;

    @Autowired
    private BaseInfoService baseInfoService;

    @Autowired
    private BaseRegionService baseRegionService;

    @Autowired
    private MenuContentMapper menuContentMapper;
    @Autowired
    private ContentGeneralMapper contentGeneralMapper;
    @Autowired
    private MediaMapper mediaMapper;
    @Autowired
    private SysValueSetService sysValueSetService;

    @Override
    public HallTableShowVo hallTableShow() {
        //查询 菜单数据
        SysMenu paramSysMenu = new SysMenu();
        paramSysMenu.setLevel(Sysconstant.HALL_TABLE_LEVEL);
        List<SysMenu> sysMenuList = sysMenuService.querySysMenuList(paramSysMenu);
        HallTableShowVo hallTableShowVo = new HallTableShowVo();
        hallTableShowVo.setSysMenuBaseVo(menuContentService.contenShowByMenuId(sysMenuList));
        return hallTableShowVo;
    }

    @Override
    public List<ChildrenShowVo> childrenShow(Integer parentId) {
        //查询当前节点以下所有节点
        List<ChildrenShowVo> sysMenuTreeList=sysMenuService.getChildrenBaseVoByParentId(parentId);
        return sysMenuTreeList;
    }

    @Override
    public QuerySysLogNameVo querySysLogName() {
        QuerySysLogNameVo querySysLogNameVo = new QuerySysLogNameVo();
        querySysLogNameVo.setSysName(SysValueSetEnums.SYS_NAME.getCode());
        querySysLogNameVo.setSysLogImg(sysValueSetService.queryPriorityValueByCode(SysValueSetEnums.SYS_LOG_IMG.getCode()));
        return querySysLogNameVo;
    }

    @Override
    public IPage<ContentGeneralVo> contentPageByMenu(PageRequest<ContentPageByMenuParameter> request) {
        //校验
        ContentPageByMenuParameter condition=request.getCondition();
        if(ObjectUtils.isEmpty(condition) || condition.getId()==null){
            throw new BusinessException(SystemCodeEnums.BAD_REQUEST.getKey(),"菜单id不能为空");
        }
        Integer menuId=condition.getId();
        PageRequest<ContentGeneralVo> iPage=new PageRequest<>();
        iPage.setPageNum(request.getPageNum());
        iPage.setPageSize(request.getPageSize());
        //分页查询
        IPage<ContentGeneralVo> sysMenuBaseVoIPage= menuContentService.contenShowPage(iPage,menuId);
        return sysMenuBaseVoIPage;
    }

    @Override
   public List<UpdateContentDto> teamDataVoChangeDb(TeamDataVo teamDataVo, Integer menuId) {
        List<UpdateContentDto> updateContentDtos=new ArrayList<>();
        //科研团队VO
        List<MenuContent> menuContentsVos=new ArrayList<>();
        List<ContentGeneral> contentGeneralsVos=new ArrayList<>();
        List<Media> mediasVos=new ArrayList<>();

        List<Integer> menuIds=new ArrayList<>();
        menuIds.add(TemplateContentEnums.RESEARCHTEAM_INTRODUCE.getMenuid());
        menuIds.add(TemplateContentEnums.RESEARCHTEAM_TEAMLEADER.getMenuid());
        menuIds.add(TemplateContentEnums.RESEARCHTEAM_KEYMEMBERS.getMenuid());
        //查询相关 菜单内容关联表 menu_content
        List<MenuContent> menuContents= menuContentService.queryByMenuIds(menuIds);
        Map<Integer, List<MenuContent>> menuContentsMap=menuContents.stream().collect(Collectors.groupingBy(MenuContent::getMenuId));
        //查询相关 内容表通用 content_general
        List<Integer> contentIds=menuContents.stream().map(MenuContent::getContentId).collect(Collectors.toList());
        List<ContentGeneral> contentGeneralList= contentGeneralService.queryByGeneralIds(contentIds);
        List<Integer> contentGeneralIds=contentGeneralList.stream().map(ContentGeneral::getId).collect(Collectors.toList());
        Map<Integer,ContentGeneral> contentGeneralListMap=contentGeneralList.stream().collect(Collectors.toMap(ContentGeneral::getId, Function.identity()));
        //查询相关图片表信息
        List<Media> mediaList=mediaService.queryByContentId(contentGeneralIds,MediaTypeEnums.IMG.getKey(),BizTypeEnums.CONTENT.getKey());
        Map<Integer,List<Media>> mediaListMap=mediaList.stream().collect(Collectors.groupingBy(Media::getContentId));



        //科研团队-介绍
        Integer contentIdIntroduce=menuContentsMap.get(TemplateContentEnums.RESEARCHTEAM_INTRODUCE.getMenuid()).get(0).getContentId();
        ContentGeneral contentGeneral=contentGeneralListMap.get(contentIdIntroduce);
        contentGeneral.setContent1(teamDataVo.getResearchteamIntroduce().getIntroduce());
        contentGeneralsVos.add(contentGeneral);

        //科研团队-团队带头人
        List<MenuContent> contentTeamleaders=menuContentsMap.get(TemplateContentEnums.RESEARCHTEAM_TEAMLEADER.getMenuid());
        List<Integer> teamleaderContentId=new ArrayList<>();
        if(CollectionUtil.isNotEmpty(contentTeamleaders)){
            teamleaderContentId=contentTeamleaders.stream().map(MenuContent::getContentId).collect(Collectors.toList());
        }
        List<TeamLeader> teamLeadersVo=teamDataVo.getTeamLeaders();
        //结构转换
        UpdateContentDto updateContentTeamLeaderDto=new UpdateContentDto();
        updateContentTeamLeaderDto=handleTeamLeader(teamLeadersVo,teamleaderContentId,contentGeneralListMap,mediaListMap
                ,menuContentsVos,contentGeneralsVos,mediasVos,updateContentTeamLeaderDto);
        updateContentDtos.add(updateContentTeamLeaderDto);

        //团队骨干成员VO
        List<MenuContent> keymembersMenuContentsVos=new ArrayList<>();
        List<ContentGeneral> keymembersContentGeneralsVos=new ArrayList<>();
        List<Media> keymembersMediasVos=new ArrayList<>();
        //科研团队-团队骨干成员
        List<MenuContent> contentKeymembers=menuContentsMap.get(TemplateContentEnums.RESEARCHTEAM_KEYMEMBERS.getMenuid());
        List<Integer> keymembersContentId=new ArrayList<>();
        if(CollectionUtil.isNotEmpty(contentKeymembers)){
            keymembersContentId=contentKeymembers.stream().map(MenuContent::getContentId).collect(Collectors.toList());
        }
        List<KeyMembers> keyMembersVo=teamDataVo.getKeyMembers();
        //结构转换
        UpdateContentDto updateContentKeymembersDto=new UpdateContentDto();
        updateContentKeymembersDto=handleKeymembers(keyMembersVo,keymembersContentId,contentGeneralListMap,mediaListMap,keymembersMenuContentsVos
                ,keymembersContentGeneralsVos,keymembersMediasVos,updateContentKeymembersDto);
        updateContentDtos.add(updateContentKeymembersDto);
        return updateContentDtos;
    }

    /**
     * 科研团队-团队带头人
     * @param teamLeadersVo
     * @param teamleaderContentId
     * @param contentGeneralListMap
     * @param mediaListMap
     * @param menuContentsVos
     * @param contentGeneralsVos
     * @param mediasVos
     * @param updateContentDto
     * @return
     */
    public UpdateContentDto handleTeamLeader(List<TeamLeader> teamLeadersVo, List<Integer> teamleaderContentId
            , Map<Integer, ContentGeneral> contentGeneralListMap, Map<Integer, List<Media>> mediaListMap, List<MenuContent> menuContentsVos
            , List<ContentGeneral> contentGeneralsVos, List<Media> mediasVos, UpdateContentDto updateContentDto) {
        //遍历团队带头人信息
        for (TeamLeader teamLeader : teamLeadersVo) {
            ContentGeneral contentGeneralTeamLeader = new ContentGeneral();
            contentGeneralTeamLeader.setContent1(teamLeader.getName());
            contentGeneralTeamLeader.setContent2(teamLeader.getTitle());
            contentGeneralTeamLeader.setContent3(teamLeader.getIntroduce());
            contentGeneralTeamLeader.setSortNum(teamLeader.getSortNum());
            if (StringUtils.isNotEmpty(teamLeader.getCode()) && teamleaderContentId.contains(Integer.parseInt(teamLeader.getCode()))) {
                ContentGeneral contentGeneral2 = contentGeneralListMap.get(Integer.parseInt(teamLeader.getCode()));
                //修改
                contentGeneralTeamLeader.setId(Integer.parseInt(teamLeader.getCode()));
                //图片地址变更
                List<Media> getMedia = mediaListMap.get(contentGeneral2.getId());
                if (CollectionUtil.isEmpty(getMedia)) {
                    //原本没有图片
                    Media media = new Media();
                    media.setId(IdUtil.generateNumericId());
                    log.debug("--id:" + media.getId());
                    media.setType(MediaTypeEnums.IMG.getKey());
                    media.setBizType(BizTypeEnums.CONTENT.getKey());
                    media.setImageUrl(teamLeader.getImg());
                    media.setContentId(contentGeneralTeamLeader.getId());
                    mediasVos.add(media);
                } else {
                    //原本有图片
                    Media media = new Media();
                    BeanUtils.copyProperties(getMedia.get(0), media);
                    media.setImageUrl(teamLeader.getImg());
                    mediasVos.add(media);
                }
                contentGeneralTeamLeader.setHasMedia(contentGeneral2.getHasMedia());
                contentGeneralTeamLeader.setIsInitialData(contentGeneral2.getIsInitialData());
                contentGeneralTeamLeader.setCreatedBy(contentGeneral2.getCreatedBy());
                contentGeneralTeamLeader.setUpdateTime(new Date());
            } else {
                //新增
                contentGeneralTeamLeader.setId(IdUtil.generateNumericId());
                log.debug("id:" + contentGeneralTeamLeader.getId());
                // MenuContent
                MenuContent menuContent = new MenuContent();
                menuContent.setId(IdUtil.generateNumericId());
                log.debug("id:" + menuContent.getId());
                menuContent.setMenuId(TemplateContentEnums.RESEARCHTEAM_TEAMLEADER.getMenuid());
                menuContent.setContentId(contentGeneralTeamLeader.getId());
                menuContentsVos.add(menuContent);

                //图片
                Media media = new Media();
                media.setId(IdUtil.generateNumericId());
                log.debug("id:" + media.getId());
                media.setType(MediaTypeEnums.IMG.getKey());
                media.setBizType(BizTypeEnums.CONTENT.getKey());
                media.setImageUrl(teamLeader.getImg());
                media.setContentId(contentGeneralTeamLeader.getId());
                mediasVos.add(media);
            }
            contentGeneralsVos.add(contentGeneralTeamLeader);
        }
        updateContentDto.setMenuContents(menuContentsVos);
        updateContentDto.setContentGenerals(contentGeneralsVos);
        updateContentDto.setMedias(mediasVos);

        //收集旧的 contentGeneralId
        List<String> teamLeadersVoList=teamLeadersVo.stream().map(TeamLeader::getCode).collect(Collectors.toList());
        List<Integer> convertedStringList = teamLeadersVoList.stream()
                .filter(Objects::nonNull)
                .filter(s -> s.matches("-?\\d+"))  // 只保留数字格式的字符串
                .map(Integer::parseInt)
                .collect(Collectors.toList());

        // 筛选旧数据元素
        List<Integer> deleteContentId =teamleaderContentId .stream()
                .filter(i -> !convertedStringList.contains(i))
                .collect(Collectors.toList());
        updateContentDto.setDeleteContentGeneralIds(deleteContentId);
        return updateContentDto;
    }


    /**
     * 科研团队-团队骨干成员
     * @param keyMembersVo
     * @param keymembersContentId
     * @param contentGeneralListMap
     * @param mediaListMap
     * @param menuContentsVos
     * @param contentGeneralsVos
     * @param mediasVos
     * @param updateContentDto
     * @return
     */
    public UpdateContentDto handleKeymembers(List<KeyMembers> keyMembersVo, List<Integer> keymembersContentId
            , Map<Integer, ContentGeneral> contentGeneralListMap, Map<Integer, List<Media>> mediaListMap, List<MenuContent> menuContentsVos
            , List<ContentGeneral> contentGeneralsVos, List<Media> mediasVos, UpdateContentDto updateContentDto) {
        //遍历团队骨干成员信息
        for (KeyMembers keyMembers : keyMembersVo) {
            ContentGeneral contentGeneralTeamLeader = new ContentGeneral();
            contentGeneralTeamLeader.setContent1(keyMembers.getName());
            contentGeneralTeamLeader.setContent2(keyMembers.getTitle());
            contentGeneralTeamLeader.setContent3(keyMembers.getIntroduce());
            contentGeneralTeamLeader.setSortNum(keyMembers.getSortNum());
            if (StringUtils.isNotEmpty(keyMembers.getCode()) && keymembersContentId.contains(Integer.parseInt(keyMembers.getCode()))) {
                ContentGeneral contentGeneral2 = contentGeneralListMap.get(Integer.parseInt(keyMembers.getCode()));
                //修改
                contentGeneralTeamLeader.setId(Integer.parseInt(keyMembers.getCode()));
                //图片地址变更
                List<Media> getMedia = mediaListMap.get(contentGeneral2.getId());
                if (CollectionUtil.isEmpty(getMedia)) {
                    //原本没有图片
                    Media media = new Media();
                    media.setId(IdUtil.generateNumericId());
                    log.debug("--id:" + media.getId());
                    media.setType(MediaTypeEnums.IMG.getKey());
                    media.setBizType(BizTypeEnums.CONTENT.getKey());
                    media.setImageUrl(keyMembers.getImg());
                    media.setContentId(contentGeneralTeamLeader.getId());
                    mediasVos.add(media);
                } else {
                    //原本有图片
                    Media media = new Media();
                    BeanUtils.copyProperties(getMedia.get(0), media);
                    media.setImageUrl(keyMembers.getImg());
                    mediasVos.add(media);
                }
                contentGeneralTeamLeader.setHasMedia(contentGeneral2.getHasMedia());
                contentGeneralTeamLeader.setIsInitialData(contentGeneral2.getIsInitialData());
                contentGeneralTeamLeader.setCreatedBy(contentGeneral2.getCreatedBy());
                contentGeneralTeamLeader.setUpdateTime(new Date());
            } else {
                //新增
                contentGeneralTeamLeader.setId(IdUtil.generateNumericId());
                log.debug("id:" + contentGeneralTeamLeader.getId());
                // MenuContent
                MenuContent menuContent = new MenuContent();
                menuContent.setId(IdUtil.generateNumericId());
                log.debug("id:" + menuContent.getId());
                menuContent.setMenuId(TemplateContentEnums.RESEARCHTEAM_KEYMEMBERS.getMenuid());
                menuContent.setContentId(contentGeneralTeamLeader.getId());
                menuContentsVos.add(menuContent);

                //图片
                Media media = new Media();
                media.setId(IdUtil.generateNumericId());
                log.debug("id:" + media.getId());
                media.setType(MediaTypeEnums.IMG.getKey());
                media.setBizType(BizTypeEnums.CONTENT.getKey());
                media.setImageUrl(keyMembers.getImg());
                media.setContentId(contentGeneralTeamLeader.getId());
                mediasVos.add(media);
            }
            contentGeneralsVos.add(contentGeneralTeamLeader);
        }

        //收集旧的 contentGeneralId
        List<String> teamLeadersVoList=keyMembersVo.stream().map(KeyMembers::getCode).collect(Collectors.toList());
        List<Integer> convertedStringList = teamLeadersVoList.stream()
                .filter(Objects::nonNull)
                .filter(s -> s.matches("-?\\d+"))  // 只保留数字格式的字符串
                .map(Integer::parseInt)
                .collect(Collectors.toList());

        // 筛选旧数据元素
        List<Integer> deleteContentId =keymembersContentId .stream()
                .filter(i -> !convertedStringList.contains(i))
                .collect(Collectors.toList());
        updateContentDto.setDeleteContentGeneralIds(deleteContentId);

        updateContentDto.setMenuContents(menuContentsVos);
        updateContentDto.setContentGenerals(contentGeneralsVos);
        updateContentDto.setMedias(mediasVos);
        return updateContentDto;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateContentDto(List<UpdateContentDto> updateContentDtos) {
        try{
            List<MenuContent> menuContents = new ArrayList<>();
            List<ContentGeneral> contentGenerals = new ArrayList<>();
            List<Media> medias = new ArrayList<>();
            List<Integer> deleteContentGeneralIds = new ArrayList<>();
            for (UpdateContentDto updateContentDto : updateContentDtos) {
                if (ObjectUtils.isNotEmpty(updateContentDto.getMenuContents())) {
                    menuContents.addAll(updateContentDto.getMenuContents());
                }
                if (ObjectUtils.isNotEmpty(updateContentDto.getContentGenerals())) {
                    contentGenerals.addAll(updateContentDto.getContentGenerals());
                }
                if (ObjectUtils.isNotEmpty(updateContentDto.getMedias())) {
                    medias.addAll(updateContentDto.getMedias());
                }
                if (CollectionUtil.isNotEmpty(updateContentDto.getDeleteContentGeneralIds())) {
                    deleteContentGeneralIds.addAll(updateContentDto.getDeleteContentGeneralIds());
                }
            }
            //因为逻辑属于全量新增，因此需要情况之前所有相关数据
            if(CollectionUtil.isNotEmpty(deleteContentGeneralIds)){
                menuContentService.deleteByContentId(deleteContentGeneralIds);
            }
            if(CollectionUtil.isNotEmpty(menuContents)){
                menuContentService.saveUpdataById(menuContents);
            }
            if(CollectionUtil.isNotEmpty(contentGenerals)){
                contentGeneral.saveUpdateById(contentGenerals);
            }
            if(CollectionUtil.isNotEmpty(medias)){
                mediaService.saveUpdateById(medias);
            }
        }catch (Exception e){
          log.error("updateContentDto,err:"+e.getMessage());
          throw new RuntimeException();
        }
    }

    @Override
    public List<UpdateContentDto> achievementVoChangeDb(AchievementDataVo achievementDataVo, Integer menuId) {
        List<UpdateContentDto> updateContentDtos=new ArrayList<>();
        List<Integer> menuIds=new ArrayList<>();
        menuIds.add(TemplateContentEnums.ACHIEVEMENTS_INTRODUCE.getMenuid());
        menuIds.add(TemplateContentEnums.ACHIEVEMENTS_REPRESENTATIVE.getMenuid());
        menuIds.add(TemplateContentEnums.REPRESENTATIVENESS_REPRESENTATIVE.getMenuid());
        menuIds.add(TemplateContentEnums.PATENTABILITY_REPRESENTATIVE.getMenuid());
        menuIds.add(TemplateContentEnums.PAPER_REPRESENTATIVE.getMenuid());
        menuIds.add(TemplateContentEnums.ACHIEVEMENTS_RESOURCES.getMenuid());
        //查询相关 菜单内容关联表 menu_content
        List<MenuContent> menuContents= menuContentService.queryByMenuIds(menuIds);
        Map<Integer, List<MenuContent>> menuContentsMap=menuContents.stream().collect(Collectors.groupingBy(MenuContent::getMenuId));
        //查询相关 内容表通用 content_general
        List<Integer> contentIds=menuContents.stream().map(MenuContent::getContentId).collect(Collectors.toList());
        List<ContentGeneral> contentGeneralList= contentGeneralService.queryByGeneralIds(contentIds);
        List<Integer> contentGeneralIds=contentGeneralList.stream().map(ContentGeneral::getId).collect(Collectors.toList());
        Map<Integer,ContentGeneral> contentGeneralListMap=contentGeneralList.stream().collect(Collectors.toMap(ContentGeneral::getId, Function.identity()));
        //查询相关图片表信息
        List<Media> mediaList=mediaService.queryByContentId(contentGeneralIds,MediaTypeEnums.IMG.getKey(),BizTypeEnums.CONTENT.getKey());
        Map<Integer,List<Media>> mediaListMap=mediaList.stream().collect(Collectors.groupingBy(Media::getContentId));

        //科研成果-介绍
        List<ContentGeneral> contentGeneralsVos=new ArrayList<>();
        Integer contentIdIntroduce=menuContentsMap.get(TemplateContentEnums.ACHIEVEMENTS_INTRODUCE.getMenuid()).get(0).getContentId();
        ContentGeneral contentGeneral=contentGeneralListMap.get(contentIdIntroduce);
        contentGeneral.setContent1(achievementDataVo.getAchievementIntroduce().getIntroduce());
        contentGeneralsVos.add(contentGeneral);
        UpdateContentDto IntroduceUpdateContentDto=new UpdateContentDto();
        IntroduceUpdateContentDto.setContentGenerals(contentGeneralsVos);
        updateContentDtos.add(IntroduceUpdateContentDto);

        //科研成果-获奖成果  representative
        List<MenuContent> contentRepresentative=menuContentsMap.get(TemplateContentEnums.ACHIEVEMENTS_REPRESENTATIVE.getMenuid());
        List<Integer> representativeContentIds=new ArrayList<>();
        if(CollectionUtil.isNotEmpty(contentRepresentative)){
              representativeContentIds=contentRepresentative.stream().map(MenuContent::getContentId).collect(Collectors.toList());
        }
        List<RepresentativeAchievement> representativeVos=achievementDataVo.getRepresentativeAchievementList();
        List<AchievementData> achievementData=assembleRepresentativeAchievement(representativeVos,TemplateContentEnums.ACHIEVEMENTS_REPRESENTATIVE.getMenuid());

        //结构转换
        UpdateContentDto representativeUpdateContentDto=new UpdateContentDto();
        representativeUpdateContentDto=handleRepresentative(achievementData,representativeContentIds,contentGeneralListMap,mediaListMap
               ,representativeUpdateContentDto,TemplateContentEnums.ACHIEVEMENTS_REPRESENTATIVE.getMenuid());
        updateContentDtos.add(representativeUpdateContentDto);

        //科研成果-代表性性成果 represent
        List<MenuContent> representativenessMenuContent=menuContentsMap.get(TemplateContentEnums.REPRESENTATIVENESS_REPRESENTATIVE.getMenuid());
        List<Integer> representativenessContentIds=new ArrayList<>();
        if(CollectionUtil.isNotEmpty(representativenessMenuContent)){
              representativenessContentIds=representativenessMenuContent.stream().map(MenuContent::getContentId).collect(Collectors.toList());
        }
        List<AchievementData> achievementDataRepresentativeness=assembleRepresentativeAchievement(representativeVos,TemplateContentEnums.REPRESENTATIVENESS_REPRESENTATIVE.getMenuid());
        //结构转换
        UpdateContentDto representativenessUpdateContentDto=new UpdateContentDto();
        representativenessUpdateContentDto=handleRepresentative(achievementDataRepresentativeness,representativenessContentIds,contentGeneralListMap,mediaListMap
                ,representativenessUpdateContentDto,TemplateContentEnums.REPRESENTATIVENESS_REPRESENTATIVE.getMenuid());
        updateContentDtos.add(representativenessUpdateContentDto);

        //科研成果-专利性成果 patentability
        List<MenuContent> patentabilityMenuContent=menuContentsMap.get(TemplateContentEnums.PATENTABILITY_REPRESENTATIVE.getMenuid());
        List<Integer> patentabilityContentIds=new ArrayList<>();
        if(CollectionUtil.isNotEmpty(patentabilityMenuContent)){
             patentabilityContentIds=patentabilityMenuContent.stream().map(MenuContent::getContentId).collect(Collectors.toList());
        }
        List<AchievementData> achievementDataRepresentative=assembleRepresentativeAchievement(representativeVos,TemplateContentEnums.PATENTABILITY_REPRESENTATIVE.getMenuid());
        //结构转换
        UpdateContentDto patentabilityUpdateContentDto=new UpdateContentDto();
        patentabilityUpdateContentDto=handleRepresentative(achievementDataRepresentative,patentabilityContentIds,contentGeneralListMap,mediaListMap
               ,patentabilityUpdateContentDto,TemplateContentEnums.PATENTABILITY_REPRESENTATIVE.getMenuid());
        updateContentDtos.add(patentabilityUpdateContentDto);

        //科研成果-论文性成果 paper
        List<MenuContent> paperMenuContent=menuContentsMap.get(TemplateContentEnums.PAPER_REPRESENTATIVE.getMenuid());
        List<Integer> paperContentIds=new ArrayList<>();
        if(CollectionUtil.isNotEmpty(paperMenuContent)){
             paperContentIds=paperMenuContent.stream().map(MenuContent::getContentId).collect(Collectors.toList());
        }
        List<AchievementData> achievementDataPaper=assembleRepresentativeAchievement(representativeVos,TemplateContentEnums.PAPER_REPRESENTATIVE.getMenuid());

        //结构转换
        UpdateContentDto paperUpdateContentDto=new UpdateContentDto();
        paperUpdateContentDto=handleRepresentative(achievementDataPaper,paperContentIds,contentGeneralListMap,mediaListMap
               ,paperUpdateContentDto,TemplateContentEnums.PAPER_REPRESENTATIVE.getMenuid());
        updateContentDtos.add(paperUpdateContentDto);

        //科研成果-资源保护
        List<MenuContent> resourceMenuContentsVos=new ArrayList<>();
        List<ContentGeneral> resourceContentGeneralsVos=new ArrayList<>();
        List<Media> resourceMediasVos=new ArrayList<>();
        //科研成果-资源保护
        List<MenuContent> contentResource=menuContentsMap.get(TemplateContentEnums.ACHIEVEMENTS_RESOURCES.getMenuid());
        List<Integer> resourceContentId=new ArrayList<>();
        if(CollectionUtil.isNotEmpty(contentResource)){
            resourceContentId=contentResource.stream().map(MenuContent::getContentId).collect(Collectors.toList());
        }
        List<ResourceProtection> resourceVoList=achievementDataVo.getResourceProtectionList();
        //结构转换
        UpdateContentDto updateContentResourceDto=new UpdateContentDto();
        updateContentResourceDto=handleResources(resourceVoList,resourceContentId,contentGeneralListMap,mediaListMap,resourceMenuContentsVos
                ,resourceContentGeneralsVos,resourceMediasVos,updateContentResourceDto);
        updateContentDtos.add(updateContentResourceDto);
        return updateContentDtos;
    }

    @Override
    public BaseImgDataDto baseImgChangeDb(List<BaseImgData> baseImgDats, Integer menuId) {
        Date nowDate=new Date();
        BaseImgDataDto baseImgDataDto=new BaseImgDataDto();
        List<BaseInfo> baseInfos=new ArrayList<>();
        List<Media> medias=new ArrayList<>();
//        //校验 系统菜单业务类型表
//       SysMenuBizType sysMenuBizType= sysMenuService.getBizTypeByMenuId(menuId);
//       if(ObjectUtils.isEmpty(sysMenuBizType)){
//            throw new BusinessException("500","系统初始化数据未完成，不能进行该操作！");
//       }
//       //校验 相关基地区域数据
//        BaseRegion region=new BaseRegion();
//        region.setMenuId(menuId);
//        List<BaseRegion> baseRegionList=baseRegionService.getBaseRegionBy(region);
//        if(CollectionUtil.isEmpty(baseRegionList)){
//            throw new BusinessException("500","系统初始化数据未完成，不能进行该操作！");
//        }
//       //查询对应基地数据
//        List<BaseInfo> baseInfoList= baseInfoService.queryBaseInfoByRegionid(baseRegionList.stream().map(BaseRegion::getId).collect(Collectors.toList()));
//        if(CollectionUtil.isEmpty(baseInfoList)){
//            throw new BusinessException("500"," 基地数据为空，不能执行修改操作！");
//        }
        //校验并查询相关基地数据
        List<BaseInfo>  baseInfoDbList=this.checkBaseInfoByMenuId(menuId);
        Map<Integer,BaseInfo> baseInfoListMap=baseInfoDbList.stream().collect(Collectors.toMap(BaseInfo::getId,Function.identity()));
       //查询对应图片数据
        List<Integer> contentGeneralIds=baseImgDats.stream().map(BaseImgData::getCode).collect(Collectors.toList());
        List<Integer> baseInfoDbIds=baseInfoDbList.stream().map(BaseInfo::getId).collect(Collectors.toList());
        //取交集idList
        Set<Integer> intersectionList= ListUtil.getUniqueIntersection(baseInfoDbIds,contentGeneralIds);

        List<Media> mediaList= mediaService.queryByContentId(contentGeneralIds,MediaTypeEnums.IMG.getKey(),BizTypeEnums.BASE.getKey());
        Map<Integer,Media>  mediaListMap=mediaList.stream().collect(Collectors.toMap(Media::getBaseId,Function.identity()));

        for(BaseImgData baseImgData:baseImgDats){
           if(baseImgData.getCode()!=null && contentGeneralIds.contains(baseImgData.getCode())){
             //更新
               BaseInfo baseInfo1=new BaseInfo();
               BeanUtils.copyProperties(baseInfoListMap.get(baseImgData.getCode()),baseInfo1);
               baseInfo1.setBaseName(baseImgData.getBaseName());
               baseInfo1.setVarietyName(baseImgData.getVarietyName());
               baseInfo1.setBaseInfo(baseImgData.getBaseInfo());
               baseInfos.add(baseInfo1);
               //照片
               Media media=mediaListMap.get(baseInfo1.getId());
               if(ObjectUtils.isNotEmpty(media)){
                   //存在照片
                   media.setImageUrl(baseImgData.getBaseImg());
                   media.setUpdateTime(nowDate);
               }else{
                   //不存在照片
                   media=new Media();
                   media.setId(IdUtil.generateNumericId());
                   media.setType(MediaTypeEnums.IMG.getKey());
                   media.setBizType(BizTypeEnums.BASE.getKey());
                   media.setImageUrl(baseImgData.getBaseImg());
                   media.setBaseId(baseInfo1.getId());
               }
               medias.add(media);
           }
//           else{
//               //新增
//               BaseInfo baseInfo1 = new BaseInfo();
//               baseInfo1.setId(IdUtil.generateNumericId());
//               baseInfo1.setMenuId(menuId);
//               baseInfo1.setBaseTypeId(sysMenuBizType.getId());
//               baseInfo1.setBaseName(baseImgData.getBaseName());
//               baseInfo1.setVarietyName(baseImgData.getVarietyName());
//               baseInfo1.setBaseInfo(baseImgData.getBaseInfo());
//               baseInfos.add(baseInfo1);
//               //照片
//               Media media = new Media();
//               //不存在照片
//               media.setId(IdUtil.generateNumericId());
//               media.setType(MediaTypeEnums.IMG.getKey());
//               media.setBizType(BizTypeEnums.BASE.getKey());
//               media.setImageUrl(baseImgData.getBaseImg());
//               media.setBaseId(baseInfo1.getId());
//               medias.add(media);
//           }
       }
        baseImgDataDto.setBaseInfos(baseInfos);
        baseImgDataDto.setMedias(medias);
        List<Integer> delMediaIds=intersectionList.stream().collect(Collectors.toList());
        baseImgDataDto.setDelMediaIds(delMediaIds);
        return baseImgDataDto;
    }

    /**
     * 根据菜单id查询对应的基地数据
     * @param menuId
     * @return
     */
    @Override
    public  List<BaseInfo> checkBaseInfoByMenuId(Integer menuId){
        //校验 系统菜单业务类型表
        SysMenuBizType sysMenuBizType= sysMenuService.getBizTypeByMenuId(menuId);
        if(ObjectUtils.isEmpty(sysMenuBizType)){
            throw new BusinessException("500","系统初始化数据未完成，不能进行该操作！");
        }
        //校验 相关基地区域数据
        BaseRegion region=new BaseRegion();
        region.setMenuId(menuId);
        List<BaseRegion> baseRegionList=baseRegionService.getBaseRegionBy(region);
        if(CollectionUtil.isEmpty(baseRegionList)){
            throw new BusinessException("500","系统初始化数据未完成，不能进行该操作！");
        }
        //查询对应基地数据
        List<BaseInfo> baseInfoList= baseInfoService.queryBaseInfoByRegionid(baseRegionList.stream().map(BaseRegion::getId).collect(Collectors.toList()));
        if(CollectionUtil.isEmpty(baseInfoList)){
            throw new BusinessException("500"," 基地数据为空，不能执行修改操作！");
        }
        return baseInfoList;
    }


    /**
     * 组装数据
     * @param representativeVos
     * @param menuid
     * @return
     */
    private List<AchievementData> assembleRepresentativeAchievement(List<RepresentativeAchievement> representativeVos, Integer menuid) {
        List<AchievementData> achievementDataList = new ArrayList<>();
        if (TemplateContentEnums.ACHIEVEMENTS_REPRESENTATIVE.getMenuid().equals(menuid)) {
            for (RepresentativeAchievement representativeAchievement : representativeVos) {
                if (StringUtils.isEmpty(representativeAchievement.getCode()) && StringUtils.isEmpty(representativeAchievement.getImg())) {
                    continue;
                } else {
                    AchievementData achievementData = new AchievementData();
                    achievementData.setCode(representativeAchievement.getCode());
                    achievementData.setImg(representativeAchievement.getImg());
                    achievementDataList.add(achievementData);
                }
            }
            return achievementDataList;
        } else if (TemplateContentEnums.REPRESENTATIVENESS_REPRESENTATIVE.getMenuid().equals(menuid)) {
            for (RepresentativeAchievement representativeAchievement : representativeVos) {
                if (StringUtils.isEmpty(representativeAchievement.getStandardCode()) && StringUtils.isEmpty(representativeAchievement.getStandardImg())) {
                    continue;
                } else {
                    AchievementData achievementData = new AchievementData();
                    achievementData.setCode(representativeAchievement.getStandardCode());
                    achievementData.setImg(representativeAchievement.getStandardImg());
                    achievementDataList.add(achievementData);
                }
            }
            return achievementDataList;
        } else if (TemplateContentEnums.PATENTABILITY_REPRESENTATIVE.getMenuid().equals(menuid)) {
            for (RepresentativeAchievement representativeAchievement : representativeVos) {
                if (StringUtils.isEmpty(representativeAchievement.getPatentCode()) && StringUtils.isEmpty(representativeAchievement.getPatentImg())) {
                    continue;
                } else {
                    AchievementData achievementData = new AchievementData();
                    achievementData.setCode(representativeAchievement.getPatentCode());
                    achievementData.setImg(representativeAchievement.getPatentImg());
                    achievementDataList.add(achievementData);
                }
            }
            return achievementDataList;
        } else if (TemplateContentEnums.PAPER_REPRESENTATIVE.getMenuid().equals(menuid)) {
            for (RepresentativeAchievement representativeAchievement : representativeVos) {
                if (StringUtils.isEmpty(representativeAchievement.getPaperCode()) && StringUtils.isEmpty(representativeAchievement.getPaperImg())) {
                    continue;
                } else {
                    AchievementData achievementData = new AchievementData();
                    achievementData.setCode(representativeAchievement.getPaperCode());
                    achievementData.setImg(representativeAchievement.getPaperImg());
                    achievementDataList.add(achievementData);
                }
            }
            return achievementDataList;
        }else {
            return null;
        }
    }

//    /**
//     * 科研成果-论文性成果
//     * @param representativeVos
//     * @param paperContentIds
//     * @param contentGeneralListMap
//     * @param mediaListMap
//     * @param paperUpdateContentDto
//     * @return
//     */
//    private UpdateContentDto handlerPaper(List<AchievementData> representativeVos, List<Integer> paperContentIds, Map<Integer, ContentGeneral> contentGeneralListMap, Map<Integer, List<Media>> mediaListMap,  UpdateContentDto paperUpdateContentDto) {
//        List<MenuContent> menuContentsVos=new ArrayList<>();
//        List<ContentGeneral> contentGeneralsVos=new ArrayList<>();
//        List<Media> mediasVos=new ArrayList<>();
//        //遍历 科研成果-论文性成果
//        for (AchievementData representative : representativeVos) {
//            ContentGeneral contentGeneralTeamLeader = new ContentGeneral();
//            if (StringUtils.isNotEmpty(representative.getCode()) && paperContentIds.contains(Integer.parseInt(representative.getCode()))) {
//                ContentGeneral contentGeneral2 = contentGeneralListMap.get(Integer.parseInt(representative.getCode()));
//                //修改
//                contentGeneralTeamLeader.setId(Integer.parseInt(representative.getCode()));
//                //图片地址变更
//                List<Media> getMedia = mediaListMap.get(contentGeneral2.getId());
//                if (CollectionUtil.isEmpty(getMedia)) {
//                    //原本没有图片
//                    Media media = new Media();
//                    media.setId(IdUtil.generateNumericId());
//                    media.setType(MediaTypeEnums.IMG.getKey());
//                    media.setBizType(BizTypeEnums.CONTENT.getKey());
//                    media.setImageUrl(representative.getImg());
//                    media.setContentId(contentGeneralTeamLeader.getId());
//                    mediasVos.add(media);
//                } else {
//                    //原本有图片
//                    Media media = new Media();
//                    BeanUtils.copyProperties(getMedia.get(0), media);
//                    media.setImageUrl(representative.getImg());
//                    mediasVos.add(media);
//                }
//                contentGeneralTeamLeader.setHasMedia(contentGeneral2.getHasMedia());
//                contentGeneralTeamLeader.setIsInitialData(contentGeneral2.getIsInitialData());
//                contentGeneralTeamLeader.setCreatedBy(contentGeneral2.getCreatedBy());
//                contentGeneralTeamLeader.setUpdateTime(new Date());
//            } else {
//                //新增
//                contentGeneralTeamLeader.setId(IdUtil.generateNumericId());
//                // MenuContent
//                MenuContent menuContent = new MenuContent();
//                menuContent.setId(IdUtil.generateNumericId());
//                menuContent.setMenuId(TemplateContentEnums.PAPER_REPRESENTATIVE.getMenuid());
//                menuContent.setContentId(contentGeneralTeamLeader.getId());
//                menuContentsVos.add(menuContent);
//                //图片
//                Media media = new Media();
//                media.setId(IdUtil.generateNumericId());
//                media.setType(MediaTypeEnums.IMG.getKey());
//                media.setBizType(BizTypeEnums.CONTENT.getKey());
//                media.setImageUrl(representative.getImg());
//                media.setContentId(contentGeneralTeamLeader.getId());
//                mediasVos.add(media);
//            }
//            contentGeneralsVos.add(contentGeneralTeamLeader);
//        }
//        paperUpdateContentDto.setMenuContents(menuContentsVos);
//        paperUpdateContentDto.setContentGenerals(contentGeneralsVos);
//        paperUpdateContentDto.setMedias(mediasVos);
//        return paperUpdateContentDto;
//    }

//    /**
//     * 科研成果-专利性成果
//     * @param representativeVos
//     * @param patentabilityContentIds
//     * @param contentGeneralListMap
//     * @param mediaListMap
//     * @param patentabilityUpdateContentDto
//     * @return
//     */
//    private UpdateContentDto handlerPatentability( List<AchievementData> representativeVos, List<Integer> patentabilityContentIds, Map<Integer, ContentGeneral> contentGeneralListMap, Map<Integer, List<Media>> mediaListMap,UpdateContentDto patentabilityUpdateContentDto) {
//        List<MenuContent> menuContentsVos=new ArrayList<>();
//        List<ContentGeneral> contentGeneralsVos=new ArrayList<>();
//        List<Media> mediasVos=new ArrayList<>();
//        //遍历 科研成果-专利性成果
//        for (AchievementData representative : representativeVos) {
//            ContentGeneral contentGeneralTeamLeader = new ContentGeneral();
//            if (StringUtils.isNotEmpty(representative.getCode()) && patentabilityContentIds.contains(Integer.parseInt(representative.getCode()))) {
//                ContentGeneral contentGeneral2 = contentGeneralListMap.get(Integer.parseInt(representative.getCode()));
//                //修改
//                contentGeneralTeamLeader.setId(Integer.parseInt(representative.getCode()));
//                //图片地址变更
//                List<Media> getMedia = mediaListMap.get(contentGeneral2.getId());
//                if (CollectionUtil.isEmpty(getMedia)) {
//                    //原本没有图片
//                    Media media = new Media();
//                    media.setId(IdUtil.generateNumericId());
//                    media.setType(MediaTypeEnums.IMG.getKey());
//                    media.setBizType(BizTypeEnums.CONTENT.getKey());
//                    media.setImageUrl(representative.getImg());
//                    media.setContentId(contentGeneralTeamLeader.getId());
//                    mediasVos.add(media);
//                } else {
//                    //原本有图片
//                    Media media = new Media();
//                    BeanUtils.copyProperties(getMedia.get(0), media);
//                    media.setImageUrl(representative.getImg());
//                    mediasVos.add(media);
//                }
//                contentGeneralTeamLeader.setHasMedia(contentGeneral2.getHasMedia());
//                contentGeneralTeamLeader.setIsInitialData(contentGeneral2.getIsInitialData());
//                contentGeneralTeamLeader.setCreatedBy(contentGeneral2.getCreatedBy());
//                contentGeneralTeamLeader.setUpdateTime(new Date());
//            } else {
//                //新增
//                contentGeneralTeamLeader.setId(IdUtil.generateNumericId());
//                // MenuContent
//                MenuContent menuContent = new MenuContent();
//                menuContent.setId(IdUtil.generateNumericId());
//                menuContent.setMenuId(TemplateContentEnums.PATENTABILITY_REPRESENTATIVE.getMenuid());
//                menuContent.setContentId(contentGeneralTeamLeader.getId());
//                menuContentsVos.add(menuContent);
//                //图片
//                Media media = new Media();
//                media.setId(IdUtil.generateNumericId());
//                media.setType(MediaTypeEnums.IMG.getKey());
//                media.setBizType(BizTypeEnums.CONTENT.getKey());
//                media.setImageUrl(representative.getImg());
//                media.setContentId(contentGeneralTeamLeader.getId());
//                mediasVos.add(media);
//            }
//            contentGeneralsVos.add(contentGeneralTeamLeader);
//        }
//        patentabilityUpdateContentDto.setMenuContents(menuContentsVos);
//        patentabilityUpdateContentDto.setContentGenerals(contentGeneralsVos);
//        patentabilityUpdateContentDto.setMedias(mediasVos);
//        return patentabilityUpdateContentDto;
//    }

//    /**
//     * 科研成果-代表性性成果
//     * @param representativeVos
//     * @param representativenessContentIds
//     * @param contentGeneralListMap
//     * @param mediaListMap
//     * @param representativenessUpdateContentDto
//     * @return
//     */
//    private UpdateContentDto handlerRepresentativeness(List<AchievementData> representativeVos, List<Integer> representativenessContentIds, Map<Integer, ContentGeneral> contentGeneralListMap, Map<Integer, List<Media>> mediaListMap, UpdateContentDto representativenessUpdateContentDto) {
//        List<MenuContent> menuContentsVos = new ArrayList<>();
//        List<ContentGeneral> contentGeneralsVos = new ArrayList<>();
//        List<Media> mediasVos = new ArrayList<>();
//        //遍历 科研成果-代表性标准
//        for (AchievementData representative : representativeVos) {
//            ContentGeneral contentGeneralTeamLeader = new ContentGeneral();
//            if (StringUtils.isNotEmpty(representative.getCode()) && representativenessContentIds.contains(Integer.parseInt(representative.getCode()))) {
//                ContentGeneral contentGeneral2 = contentGeneralListMap.get(Integer.parseInt(representative.getCode()));
//                //修改
//                contentGeneralTeamLeader.setId(Integer.parseInt(representative.getCode()));
//                //图片地址变更
//                List<Media> getMedia = mediaListMap.get(contentGeneral2.getId());
//                if (CollectionUtil.isEmpty(getMedia)) {
//                    //原本没有图片
//                    Media media = new Media();
//                    media.setId(IdUtil.generateNumericId());
//                    media.setType(MediaTypeEnums.IMG.getKey());
//                    media.setBizType(BizTypeEnums.CONTENT.getKey());
//                    media.setImageUrl(representative.getImg());
//                    media.setContentId(contentGeneralTeamLeader.getId());
//                    mediasVos.add(media);
//                } else {
//                    //原本有图片
//                    Media media = new Media();
//                    BeanUtils.copyProperties(getMedia.get(0), media);
//                    media.setImageUrl(representative.getImg());
//                    mediasVos.add(media);
//                }
//                contentGeneralTeamLeader.setHasMedia(contentGeneral2.getHasMedia());
//                contentGeneralTeamLeader.setIsInitialData(contentGeneral2.getIsInitialData());
//                contentGeneralTeamLeader.setCreatedBy(contentGeneral2.getCreatedBy());
//                contentGeneralTeamLeader.setUpdateTime(new Date());
//            } else {
//                //新增
//                contentGeneralTeamLeader.setId(IdUtil.generateNumericId());
//                // MenuContent
//                MenuContent menuContent = new MenuContent();
//                menuContent.setId(IdUtil.generateNumericId());
//                menuContent.setMenuId(TemplateContentEnums.REPRESENTATIVENESS_REPRESENTATIVE.getMenuid());
//                menuContent.setContentId(contentGeneralTeamLeader.getId());
//                menuContentsVos.add(menuContent);
//                //图片
//                Media media = new Media();
//                media.setId(IdUtil.generateNumericId());
//                media.setType(MediaTypeEnums.IMG.getKey());
//                media.setBizType(BizTypeEnums.CONTENT.getKey());
//                media.setImageUrl(representative.getImg());
//                media.setContentId(contentGeneralTeamLeader.getId());
//                mediasVos.add(media);
//            }
//            contentGeneralsVos.add(contentGeneralTeamLeader);
//        }
//        representativenessUpdateContentDto.setMenuContents(menuContentsVos);
//        representativenessUpdateContentDto.setContentGenerals(contentGeneralsVos);
//        representativenessUpdateContentDto.setMedias(mediasVos);
//        return representativenessUpdateContentDto;
//    }

    private UpdateContentDto handleResources(List<ResourceProtection> resourceVoList, List<Integer> resourceContentId, Map<Integer, ContentGeneral> contentGeneralListMap, Map<Integer, List<Media>> mediaListMap, List<MenuContent> resourceMenuContentsVos, List<ContentGeneral> resourceContentGeneralsVos, List<Media> resourceMediasVos, UpdateContentDto updateContentResourceDto) {
        //遍历资源保护信息
        for (ResourceProtection resourceProtection : resourceVoList) {
            ContentGeneral contentGeneral = new ContentGeneral();
            contentGeneral.setContent1(resourceProtection.getTitle());
            contentGeneral.setContent2(resourceProtection.getIntroduce());
            if (StringUtils.isNotEmpty(resourceProtection.getCode()) && resourceContentId.contains(Integer.parseInt(resourceProtection.getCode()))) {
                ContentGeneral contentGeneral2 = contentGeneralListMap.get(Integer.parseInt(resourceProtection.getCode()));
                //修改
                contentGeneral.setId(Integer.parseInt(resourceProtection.getCode()));
                //图片地址变更
                List<Media> getMedia = mediaListMap.get(contentGeneral2.getId());
                if (CollectionUtil.isEmpty(getMedia)) {
                    //原本没有图片
                    Media media = new Media();
                    media.setId(IdUtil.generateNumericId());
                    log.debug("--id:" + media.getId());
                    media.setType(MediaTypeEnums.IMG.getKey());
                    media.setBizType(BizTypeEnums.CONTENT.getKey());
                    media.setImageUrl(resourceProtection.getImg());
                    media.setContentId(contentGeneral.getId());
                    resourceMediasVos.add(media);
                } else {
                    //原本有图片
                    Media media = new Media();
                    BeanUtils.copyProperties(getMedia.get(0), media);
                    media.setImageUrl(resourceProtection.getImg());
                    resourceMediasVos.add(media);
                }
                contentGeneral.setHasMedia(contentGeneral2.getHasMedia());
                contentGeneral.setIsInitialData(contentGeneral2.getIsInitialData());
                contentGeneral.setCreatedBy(contentGeneral2.getCreatedBy());
                contentGeneral.setUpdateTime(new Date());
            } else {
                //新增
                contentGeneral.setId(IdUtil.generateNumericId());
                log.debug("id:" + contentGeneral.getId());
                // MenuContent
                MenuContent menuContent = new MenuContent();
                menuContent.setId(IdUtil.generateNumericId());
                log.debug("id:" + menuContent.getId());
                menuContent.setMenuId(TemplateContentEnums.ACHIEVEMENTS_RESOURCES.getMenuid());
                menuContent.setContentId(contentGeneral.getId());
                resourceMenuContentsVos.add(menuContent);

                //图片
                Media media = new Media();
                media.setId(IdUtil.generateNumericId());
                log.debug("id:" + media.getId());
                media.setType(MediaTypeEnums.IMG.getKey());
                media.setBizType(BizTypeEnums.CONTENT.getKey());
                media.setImageUrl(resourceProtection.getImg());
                media.setContentId(contentGeneral.getId());
                resourceMediasVos.add(media);
            }
            resourceContentGeneralsVos.add(contentGeneral);
        }

        //收集旧的 contentGeneralId
        List<String> teamLeadersVoList=resourceVoList.stream().map(ResourceProtection::getCode).collect(Collectors.toList());
        List<Integer> convertedStringList = teamLeadersVoList.stream()
                .filter(Objects::nonNull)
                .filter(s -> s.matches("-?\\d+"))  // 只保留数字格式的字符串
                .map(Integer::parseInt)
                .collect(Collectors.toList());

        // 筛选旧数据元素
        List<Integer> deleteContentId =resourceContentId .stream()
                .filter(i -> !convertedStringList.contains(i))
                .collect(Collectors.toList());
        updateContentResourceDto.setDeleteContentGeneralIds(deleteContentId);
        updateContentResourceDto.setMenuContents(resourceMenuContentsVos);
        updateContentResourceDto.setContentGenerals(resourceContentGeneralsVos);
        updateContentResourceDto.setMedias(resourceMediasVos);
        return updateContentResourceDto;
    }

    /**
     * 科研成果-获奖成果
     * @param representativeAchievements
     * @param representativeContentIds
     * @param contentGeneralListMap
     * @param mediaListMap
     * @param updateContentDto
     * @return
     */
    private UpdateContentDto handleRepresentative(List<AchievementData> representativeAchievements,
                                                  List<Integer> representativeContentIds,
                                                           Map<Integer, ContentGeneral> contentGeneralListMap,
                                                           Map<Integer, List<Media>> mediaListMap
                                                            ,UpdateContentDto updateContentDto,Integer menuId) {
        List<MenuContent> menuContentsVos=new ArrayList<>();
        List<ContentGeneral> contentGeneralsVos=new ArrayList<>();
        List<Media> mediasVos=new ArrayList<>();
        //遍历 科研成果-获奖成果
        for (AchievementData representative : representativeAchievements) {
            ContentGeneral contentGeneralTeamLeader = new ContentGeneral();
            if (StringUtils.isNotEmpty(representative.getCode()) && representativeContentIds.contains(Integer.parseInt(representative.getCode()))) {
                ContentGeneral contentGeneral2 = contentGeneralListMap.get(Integer.parseInt(representative.getCode()));
                //修改
                contentGeneralTeamLeader.setId(Integer.parseInt(representative.getCode()));
                //图片地址变更
                List<Media> getMedia = mediaListMap.get(contentGeneral2.getId());
                if (CollectionUtil.isEmpty(getMedia)) {
                    //原本没有图片
                    Media media = new Media();
                    media.setId(IdUtil.generateNumericId());
                    media.setType(MediaTypeEnums.IMG.getKey());
                    media.setBizType(BizTypeEnums.CONTENT.getKey());
                    media.setImageUrl(representative.getImg());
                    media.setContentId(contentGeneralTeamLeader.getId());
                    mediasVos.add(media);
                } else {
                    //原本有图片
                    Media media = new Media();
                    BeanUtils.copyProperties(getMedia.get(0), media);
                    media.setImageUrl(representative.getImg());
                    mediasVos.add(media);
                }
                contentGeneralTeamLeader.setHasMedia(contentGeneral2.getHasMedia());
                contentGeneralTeamLeader.setIsInitialData(contentGeneral2.getIsInitialData());
                contentGeneralTeamLeader.setCreatedBy(contentGeneral2.getCreatedBy());
                contentGeneralTeamLeader.setUpdateTime(new Date());
            } else {
                //新增
                contentGeneralTeamLeader.setId(IdUtil.generateNumericId());

                // MenuContent
                MenuContent menuContent = new MenuContent();
                menuContent.setId(IdUtil.generateNumericId());
                menuContent.setMenuId(menuId);
                menuContent.setContentId(contentGeneralTeamLeader.getId());
                menuContentsVos.add(menuContent);

                //图片
                Media media = new Media();
                media.setId(IdUtil.generateNumericId());
                media.setType(MediaTypeEnums.IMG.getKey());
                media.setBizType(BizTypeEnums.CONTENT.getKey());
                media.setImageUrl(representative.getImg());
                media.setContentId(contentGeneralTeamLeader.getId());
                mediasVos.add(media);
            }
            contentGeneralsVos.add(contentGeneralTeamLeader);
        }
        //收集旧的 contentGeneralId
        List<String> teamLeadersVoList=representativeAchievements.stream().map(AchievementData::getCode).collect(Collectors.toList());
        List<Integer> convertedStringList = teamLeadersVoList.stream()
                .filter(Objects::nonNull)
                .filter(s -> s.matches("-?\\d+"))  // 只保留数字格式的字符串
                .map(Integer::parseInt)
                .collect(Collectors.toList());

        // 筛选旧数据元素
        List<Integer> deleteContentId =representativeContentIds .stream()
                .filter(i -> !convertedStringList.contains(i))
                .collect(Collectors.toList());
        updateContentDto.setDeleteContentGeneralIds(deleteContentId);

        updateContentDto.setMenuContents(menuContentsVos);
        updateContentDto.setContentGenerals(contentGeneralsVos);
        updateContentDto.setMedias(mediasVos);
        return updateContentDto;
    }


//    @Override
//    public void downloadByMenu(HttpServletResponse response, Integer menuId) {
//        try {
//            //校验菜单是否可以下载模板
//            DataTemplate dataTemplate = sysMenuService.queryDataTemplateByMenuId(menuId);
//            if (ObjectUtils.isNull(dataTemplate)) {
//                throw new BusinessException(SystemCodeEnums.BAD_REQUEST.getKey(), "该菜单id无模板配置!");
//            }
//            String templateCode=dataTemplate.getTemplateCode();
//            //根据菜单构建 workbook 对象
//            if (TemplateCodeEnums.RESEARCHTEAM.getKey().equals(templateCode)) {
//                //科研团队 构建模板数据
//                researchteamXSSFWorkbook(response, menuId);
//            } else if (TemplateCodeEnums.RESEARCH_ACHIEVEMENTS.getKey().equals(templateCode)) {
//                //科研成果 构建模板数据
//                researchAchievementsXSSFWorkbook(response, menuId);
//            } else if (TemplateCodeEnums.PLACE_BASE.getKey().equals(templateCode)) {
//                //地方猪种源基地 构建模板数据
//                baseXSSFWorkbook(response, menuId);
//            } else if (TemplateCodeEnums.LEAN_MEAT_BASE.getKey().equals(templateCode)) {
//                //瘦肉型猪种源基地 构建模板数据
//                baseXSSFWorkbook(response, menuId);
//            } else if (TemplateCodeEnums.BLACK_PIG_BASE.getKey().equals(templateCode)) {
//                //黑猪盟养殖基地 构建模板数据
//                baseXSSFWorkbook(response, menuId);
//            } else if (TemplateCodeEnums.INNOVATE_BASE.getKey().equals(templateCode)) {
//                //猪种质创新基地 构建模板数据
//                baseXSSFWorkbook(response, menuId);
//            } else {
//                throw new BusinessException(SystemCodeEnums.BAD_REQUEST.getKey(), "该菜单id无模板配置!");
//            }
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//    }

//    /**
//     * 地方猪种源基地
//     * @param response
//     * @param menuId
//     */
//    private void baseXSSFWorkbook(HttpServletResponse response, Integer menuId) {
//            try {
//                XSSFWorkbook workbook = new XSSFWorkbook();
//                // Sheet 1: 种源基地数据更新模板
//                List<BaseTemplate> baseTemplateList=new ArrayList<>();
//                for(int i=0;i<10;i++){
//                    BaseTemplate baseTemplate=new BaseTemplate();
//                    baseTemplate.setCode("code"+i);
//                    baseTemplate.setImg("img"+i);
//                    baseTemplateList.add(baseTemplate);
//                }
//                createBaseSheet(workbook,baseTemplateList);
//
//                // 3. 设置响应头
//                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//                response.setHeader("Content-Disposition", "attachment; filename=report.xlsx");
//                // 4. 写入响应流
//                workbook.write(response.getOutputStream());
//                workbook.close();
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }
//    }

//    /**
//     * 种源基地数据更新模板
//     * @param workbook
//     * @param baseTemplateList
//     */
//    private void createBaseSheet(XSSFWorkbook workbook, List<BaseTemplate> baseTemplateList) {
//        XSSFSheet sheet = workbook.createSheet("种源基地数据更新模板");
//        // 创建表头  基地编码	基地名称	猪只品种	基地照片	基地介绍
//        String[] headers = {"基地编码","基地名称","猪只品种","基地照片","基地介绍"};
//        XSSFRow headerRow = sheet.createRow(0);
//        for (int i = 0; i < headers.length; i++) {
//            headerRow.createCell(i).setCellValue(headers[i]);
//        }
//        //数据填充
//        for (int i=0;i<baseTemplateList.size();i++){
//            XSSFRow row = sheet.createRow(i + 1);  // 第一行是表头，所以数据从第2行开始
//            row.createCell(0).setCellValue(baseTemplateList.get(i).getCode());
//            row.createCell(1).setCellValue(baseTemplateList.get(i).getImg());
//        }
//        XSSFRow row = sheet.createRow(baseTemplateList.size()+1+TemplateCopywritingEnums.MSG.getKey());  // 第一行是表头，所以数据从第2行开始
//        row.createCell(0).setCellValue(TemplateCopywritingEnums.MSG.getMsg());
//    }

//    /**
//     * 科研成果模板数据
//     * @param response
//     * @param menuId
//     */
//    private void researchAchievementsXSSFWorkbook(HttpServletResponse response, Integer menuId) {
//        try {
//            XSSFWorkbook workbook = new XSSFWorkbook();
//            // Sheet 1: 成果简介
//            AchievementIntroduce achievementIntroduce=new AchievementIntroduce();
//            achievementIntroduce.setIntroduce("111");
//            createAchievementIntroduceSheet(workbook, achievementIntroduce);
//
//            // Sheet 2: 代表性成果
//            List<RepresentativeAchievement> representativeAchievementList=new ArrayList<>();
//            for(int i=0;i<10;i++){
//                RepresentativeAchievement representativeAchievement=new RepresentativeAchievement();
//                representativeAchievement.setCode("code"+i);
//                representativeAchievement.setImg("img"+i);
//                representativeAchievementList.add(representativeAchievement);
//            }
//            createRepresentativeAchievementSheet(workbook,representativeAchievementList);
//
//            // Sheet 3: 资源保护
//            List<ResourceProtection> resourceProtectionList=new ArrayList<>();
//            for(int i=0;i<10;i++){
//                ResourceProtection resourceProtection=new ResourceProtection();
//                resourceProtection.setCode("code"+i);
//                resourceProtection.setImg("img"+i);
//                resourceProtectionList.add(resourceProtection);
//            }
//            createResourceProtectionSheet(workbook,resourceProtectionList);
//
//            // 3. 设置响应头
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//            response.setHeader("Content-Disposition", "attachment; filename=report.xlsx");
//            // 4. 写入响应流
//            workbook.write(response.getOutputStream());
//            workbook.close();
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//    }

//    /**
//     * 资源保护
//     *
//     * @param workbook
//     * @param resourceProtectionList
//     */
//    private void createResourceProtectionSheet(XSSFWorkbook workbook, List<ResourceProtection> resourceProtectionList) {
//        XSSFSheet sheet = workbook.createSheet("资源保护");
//        // 创建表头  编码	标题	图片	介绍
//        String[] headers = {"编码", "标题", "图片", "介绍"};
//        XSSFRow headerRow = sheet.createRow(0);
//        for (int i = 0; i < headers.length; i++) {
//            headerRow.createCell(i).setCellValue(headers[i]);
//        }
//        //数据填充
//        for (int i = 0; i < resourceProtectionList.size(); i++) {
//            XSSFRow row = sheet.createRow(i + 1);  // 第一行是表头，所以数据从第2行开始
//            row.createCell(0).setCellValue(resourceProtectionList.get(i).getCode());
//            row.createCell(1).setCellValue(resourceProtectionList.get(i).getTitle());
//            row.createCell(2).setCellValue(resourceProtectionList.get(i).getImg());
//            row.createCell(3).setCellValue(resourceProtectionList.get(i).getIntroduce());
//        }
//        XSSFRow row = sheet.createRow(resourceProtectionList.size() + 1 + TemplateCopywritingEnums.MSG.getKey());  // 第一行是表头，所以数据从第2行开始
//        row.createCell(0).setCellValue(TemplateCopywritingEnums.MSG.getMsg());
//    }

//    /**
//     * 代表性成果
//     * @param workbook
//     * @param representativeAchievementList
//     */
//    private void createRepresentativeAchievementSheet(XSSFWorkbook workbook, List<RepresentativeAchievement> representativeAchievementList) {
//        XSSFSheet sheet = workbook.createSheet("代表性成果");
//        // 创建表头  成果编码	获奖成果图片	标准编码	代表性标准图片	专利编码	代表性专利图片	论文编码	代表性论文图片
//        String[] headers = {"成果编码","获奖成果图片","标准编码","代表性标准图片","专利编码","代表性专利图片","论文编码","代表性论文图片"};
//        XSSFRow headerRow = sheet.createRow(0);
//        for (int i = 0; i < headers.length; i++) {
//            headerRow.createCell(i).setCellValue(headers[i]);
//        }
//        //数据填充
//        for (int i=0;i<representativeAchievementList.size();i++){
//            XSSFRow row = sheet.createRow(i + 1);  // 第一行是表头，所以数据从第2行开始
//            row.createCell(0).setCellValue(representativeAchievementList.get(i).getCode());
//            row.createCell(1).setCellValue(representativeAchievementList.get(i).getImg());
//        }
//        XSSFRow row = sheet.createRow(representativeAchievementList.size()+1+TemplateCopywritingEnums.MSG.getKey());  // 第一行是表头，所以数据从第2行开始
//        row.createCell(0).setCellValue(TemplateCopywritingEnums.MSG.getMsg());
//    }


//    /**
//     * 科研成果-成果简介
//     * @param workbook
//     * @param achievementIntroduce
//     */
//    private void createAchievementIntroduceSheet(XSSFWorkbook workbook, AchievementIntroduce achievementIntroduce) {
//        XSSFSheet sheet = workbook.createSheet("成果简介");
//        // 创建表头
//        String[] headers = {"成果简介"};
//        XSSFRow headerRow = sheet.createRow(0);
//        for (int i = 0; i < headers.length; i++) {
//            headerRow.createCell(i).setCellValue(headers[i]);
//        }
//        //数据填充
//        XSSFRow row = sheet.createRow( 1);
//        row.createCell(0).setCellValue(achievementIntroduce.getIntroduce());
//    }


//    /**
//     * 科研团队模板数据
//     * @param response
//     * @param menuId
//     */
//
//    public void researchteamXSSFWorkbook(HttpServletResponse response, Integer menuId) {
//        try {
//            XSSFWorkbook workbook = new XSSFWorkbook();
//            // Sheet 1: 科员团队介绍
//            ResearchteamIntroduce researchteamIntroduce=new ResearchteamIntroduce();
//            researchteamIntroduce.setIntroduce("111");
//            createEmployeeSheet(workbook, researchteamIntroduce);
//
//            // Sheet 2: 团队带头人
//            List<TeamLeader> teamLeaderList=new ArrayList<>();
//            for(int i=0;i<10;i++){
//                TeamLeader teamLeader=new TeamLeader();
//                teamLeader.setCode("code"+i);
//                teamLeader.setImg("img"+i);
//                teamLeader.setIntroduce("idc"+i);
//                teamLeader.setName("name"+i);
//                teamLeader.setTitle("title"+i);
//                teamLeaderList.add(teamLeader);
//            }
//            createTeamLeaderSheet(workbook,teamLeaderList);
//
//            // Sheet 3: 骨干成员
//            List<KeyMembers> keyMembersArrayList=new ArrayList<>();
//            for(int i=0;i<10;i++){
//                KeyMembers keyMembers=new KeyMembers();
//                keyMembers.setCode("code"+i);
//                keyMembers.setImg("img"+i);
//                keyMembers.setIntroduce("idc"+i);
//                keyMembers.setName("name"+i);
//                keyMembers.setTitle("title"+i);
//                keyMembersArrayList.add(keyMembers);
//            }
//            createKeyMembersSheet(workbook,keyMembersArrayList);
//
//            // 3. 设置响应头
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//            response.setHeader("Content-Disposition", "attachment; filename=report.xlsx");
//            // 4. 写入响应流
//            workbook.write(response.getOutputStream());
//            workbook.close();
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//    }

//    private static void createEmployeeSheet(XSSFWorkbook workbook, ResearchteamIntroduce researchteamIntroduce) throws SQLException {
//        XSSFSheet sheet = workbook.createSheet("团队介绍");
//        // 创建表头
//        String[] headers = {"团队介绍"};
//        XSSFRow headerRow = sheet.createRow(0);
//        for (int i = 0; i < headers.length; i++) {
//            headerRow.createCell(i).setCellValue(headers[i]);
//        }
//        //数据填充
//        XSSFRow row = sheet.createRow( 1);
//        row.createCell(0).setCellValue(researchteamIntroduce.getIntroduce());
//    }

//    private static void createTeamLeaderSheet(XSSFWorkbook workbook,  List<TeamLeader> teamLeaderList) throws SQLException {
//        XSSFSheet sheet = workbook.createSheet("团队带头人");
//        // 创建表头 人员编码	姓名	头衔	照片	介绍
//        String[] headers = {"人员编码","姓名","头衔","照片","介绍"};
//        XSSFRow headerRow = sheet.createRow(0);
//        for (int i = 0; i < headers.length; i++) {
//            headerRow.createCell(i).setCellValue(headers[i]);
//        }
//        //数据填充
//        for (int i=0;i<teamLeaderList.size();i++){
//            XSSFRow row = sheet.createRow(i + 1);  // 第一行是表头，所以数据从第2行开始
//            row.createCell(0).setCellValue(teamLeaderList.get(i).getCode());
//            row.createCell(1).setCellValue(teamLeaderList.get(i).getName());
//            row.createCell(2).setCellValue(teamLeaderList.get(i).getTitle());
//            row.createCell(3).setCellValue(teamLeaderList.get(i).getImg());
//            row.createCell(4).setCellValue(teamLeaderList.get(i).getIntroduce());
//        }
//        XSSFRow row = sheet.createRow(teamLeaderList.size()+1+TemplateCopywritingEnums.MSG.getKey());  // 第一行是表头，所以数据从第2行开始
//        row.createCell(0).setCellValue(TemplateCopywritingEnums.MSG.getMsg());
//
//    }

//    private static void createKeyMembersSheet(XSSFWorkbook workbook,  List<KeyMembers> KeyMembersList) throws SQLException {
//        XSSFSheet sheet = workbook.createSheet("骨干成员");
//        // 创建表头 人员编码	姓名	头衔	照片	介绍
//        String[] headers = {"人员编码","姓名","头衔","照片","介绍"};
//        XSSFRow headerRow = sheet.createRow(0);
//        for (int i = 0; i < headers.length; i++) {
//            headerRow.createCell(i).setCellValue(headers[i]);
//        }
//        //数据填充
//        for (int i=0;i<KeyMembersList.size();i++){
//            XSSFRow row = sheet.createRow(i + 1);  // 第一行是表头，所以数据从第2行开始
//            row.createCell(0).setCellValue(KeyMembersList.get(i).getCode());
//            row.createCell(1).setCellValue(KeyMembersList.get(i).getName());
//            row.createCell(2).setCellValue(KeyMembersList.get(i).getTitle());
//            row.createCell(3).setCellValue(KeyMembersList.get(i).getImg());
//            row.createCell(4).setCellValue(KeyMembersList.get(i).getIntroduce());
//        }
//        XSSFRow row = sheet.createRow(KeyMembersList.size()+1+TemplateCopywritingEnums.MSG.getKey());  // 第一行是表头，所以数据从第2行开始
//        row.createCell(0).setCellValue(TemplateCopywritingEnums.MSG.getMsg());
//    }

}




